<!--  -->
<template>
  <div id="nav" ref="navScroll">
    <div class="nav-scroll">
      <a
        v-for="item of navs"
        :key="item.name"
        :ref = "item.name"
        @click="clickHandler(item)"
        :class="{ 'router-link-exact-active': item.isActive }"
      >
        {{ item.name }}
      </a>
    </div>
  </div>
</template>

<script>
import BScroll from "@better-scroll/core";
//console.log(BScroll);
export default {
  data() {
    return {
      navs: [
        {
          id: 0,
          href: "/",
          name: "BScore",
          isActive: false,
        },
        {
          id: 1,
          href: "/mouse-wheel",
          name: "mouse-wheel",
          isActive: false,
        },
        {
          id: 2,
          href: "/scroll-bar",
          name: "scroll-bar",
          isActive: false,
        },
        {
          id: 3,
          href: "/pullup",
          name: "pullup",
          isActive: false,
        },
        {
          id: 4,
          href: "/wheel",
          name: "wheel",
          isActive: false,
        },
        {
          id: 5,
          href: "/slide",
          name: "slide",
          isActive: false,
        },
        {
          id: 6,
          href: "/nested-scroll",
          name: "nested-scroll",
          isActive: false,
        },
      ],
    };
  },
  created () {
    this.navsActiveSwitch();
  },
  mounted() {   
    this.navSwiperinit();
  },
  watch: {
    // 如果路由有变化，会再次执行该方法
    '$route': 'navsActiveSwitch'
  },
  methods: {
    navSwiperinit() {
      this.NavBscroll = new BScroll(this.$refs.navScroll, {
        scrollX: true,
        scrollY: false,
        click: true,
      });
      this.NavBscroll.on("scrollStart",()=>{
        //console.log('scroll start')
      })
    },
    navsActiveSwitch() {
      const { navs } = this;
      let name = this.$route.name;
      console.log(name);
      if(name && this.NavBscroll){
        this.NavBscroll.scrollToElement(this.$refs[name][0], 0, true)
      }
      navs.forEach((item) => {
        if (item.name === name) {
          item.isActive = true;
        } else {
          item.isActive = false;
        }
      });
    },
    clickHandler(item) {
      const { href, isActive,name } = item;
      if (!isActive) {    
        //console.log(this.$refs[name][0]) 
        this.NavBscroll.scrollToElement(this.$refs[name][0], 300, true)
        this.$router.push({ path: href });
      } else {
        console.log("正在當前頁面，禁止點擊");
        return;
      }      
    },
  },
};
</script>
